package org.diysearch.services;

import javax.servlet.http.HttpSession;

import org.diysearch.helpers.UserHelper;
import org.diysearch.interfaces.Product;
import org.diysearch.models.Status;
import org.diysearch.models.User;
import org.diysearch.products.JsonProduct;

public class Login extends BaseService {
	private String uri;
	
	@Override
	public Product execute() throws Exception {
		Product p = new JsonProduct();
		Status s = new Status();
		
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		User u = new User();
		u.setUsername(username);
		u.setPassword(password);
		User user = UserHelper.login(u);
		
		if (user == null) {
			s.setMessage("invalid login");
			s.setCode(-1);
		} else {
			s.setMessage("logged in");
			s.setCode(1);
			
			HttpSession session = request.getSession(true);
			session.setAttribute("user", user);
		}
		
		p.setWriter(writer);
		p.setOutput(s);
		
		return p;
	}

	@Override
	public boolean isWriter() {
		return true;
	}

	@Override
	public String getUri() {
		return uri;
	}

	@Override
	public void setUri(String uri) {
		this.uri = uri;
	}

}
